﻿using System;
using Combat;
using Locomotion;
using UnityEngine;
using World;

namespace Controls
{
    public class ShooterAi : MonoBehaviour
    {
        private enum State
        {
            Chasing = 0,
            Shooting = 1
        }

        [SerializeField] private float shootRange = 5f;
        
        private Health _health;
        private Mover _mover;
        private Shooter _shooter;
        
        private State _state = State.Chasing;


        private void Awake()
        {
            _health = GetComponent<Health>();
            _mover = GetComponent<Mover>();
            _shooter = GetComponent<Shooter>();
            
            _health.Died += Health_Died;
        }

        private void Update()
        {
            UpdateState();
        }
        
        private void Health_Died()
        {
            enabled = false;
        }

        private void UpdateState()
        {
            _shooter.AimAtPosition(WorldInfo.Instance.Player.position);
            
            Vector2 moveVector = WorldInfo.Instance.Player.position - transform.position;
            bool isInBound = !WorldInfo.Instance.IsOutOfBound(transform.position);
            
            switch (_state)
            {
                case State.Chasing:
                    _mover.Move(moveVector.normalized);

                    if (isInBound && moveVector.sqrMagnitude <= (shootRange - 1f) * (shootRange - 1f))
                    {
                        _state = State.Shooting;
                        _mover.StopMoving();
                    }
                    
                    break;
                case State.Shooting:
                    _shooter.Shoot();
                    
                    if (!isInBound || moveVector.sqrMagnitude > shootRange * shootRange)
                    {
                        _state = State.Chasing;
                    }
                    
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
        
        private void OnDrawGizmosSelected()
        {
            Gizmos.color = Color.red;   
            Gizmos.DrawWireSphere(transform.position, shootRange);
        }
    }
}